package com.cqie.practicaltraining.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.cqie.practicaltraining.domain.Users;
import com.cqie.practicaltraining.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 用来提供给security的用户信息的service，
 * 我们需要复写 loadUserByUsername 方法返回数据库中的用户信息
 */
@Service
public class UserDetailServiceImpl implements UserDetailsService {
    /**
     * 加载数据库中的认证的用户的信息：用户名，密码，用户的权限列表
     * @param username: 该方法把username传入进来，我们通过username查询用户的信息
    (密码，权限列表等)然后封装成 UserDetails进行返回 ，交给security 。
     */
    @Autowired
    private UserMapper UserMapper;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if (StringUtils.isBlank(username)){
            throw new UsernameNotFoundException("用户名不能为空");
        }
        LambdaQueryWrapper<Users> sysUserLambdaQueryWrapper = new LambdaQueryWrapper<>();
        sysUserLambdaQueryWrapper.eq(Users::getUserName, username);
        Users sysUser = UserMapper.selectOne(sysUserLambdaQueryWrapper);
        if (Objects.isNull(sysUser)){
            throw new UsernameNotFoundException("用户名不存在");
        }
        List<GrantedAuthority> permissions = new ArrayList<>();
        // 密码是基于BCryptPasswordEncoder加密的密文
        // User是security内部的对象，UserDetails的实现类 ，用来封装用户的基本信息（用户名，密码，权限列表）
        return new User(username, sysUser.getPassword(),permissions);
    }
}
